import hashlib
import time
import timeit


def calculate_hash(file_path: str | bytes) -> str:
    """计算文件的哈希值（使用SHA256）"""
    hash_sha256 = hashlib.sha256()
    with open(file_path, "rb") as f:  # 以二进制模式打开文件
        for chunk in iter(lambda: f.read(4096), b""):  # 读取文件的每个块
            hash_sha256.update(chunk)
    return hash_sha256.hexdigest()  # 返回十六进制哈希值

def main():
    file_path = '../source_files/aaa.txt'  # 替换为你的文件路径
    hash_file_path = '../source_files/hash.txt'  # 保存哈希值的文件路径

    # 首次计算哈希值并保存
    # file_hash = calculate_hash(file_path)
    # with open(hash_file_path, 'w') as hash_file:
    #     hash_file.write(file_hash)
    # print(f"初始哈希值已保存: {file_hash}")

    # 每次打开文件时检查哈希值
    while True:
        stored_hash = ""
        try:
            with open(hash_file_path, 'r') as hash_file:
                stored_hash = hash_file.read()
            print(f"存储的哈希值: {stored_hash}")
        except FileNotFoundError:
            print("未找到哈希值文件，将创建新的哈希值文件。")
            break

        current_hash = calculate_hash(file_path)
        print(f"当前哈希值: {current_hash}")

        if current_hash == stored_hash:
            print("文件未被更改。")
            break
            # 执行文件未更改时的操作
        else:
            print("文件已被更改！")
            # 执行文件已更改时的操作
            with open(hash_file_path, 'w') as hash_file:
                hash_file.write(current_hash)  # 更新哈希值文件
            break  # 如果文件已更改，退出循环或执行其他操作

if __name__ == "__main__":
    start_time = time.time()
    main()
    end_time = time.time()  # 记录结束时间
    elapsed_time = end_time - start_time  # 计算执行时间
    print(f"代码块执行花费的时间：{elapsed_time}秒")

    # timeit.timeit(代码, 编号=次数) 会执行代码多次并返回总时间
    # elapsed_time = timeit.timeit(main, number=10)
    # print(f"代码块平均执行花费的时间：{elapsed_time / 10}秒")